

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="分享开发的趣事">
  <meta name="author" content="RoseC(陈智豪)">
  <meta name="keywords" content="RoseC的博客,陈智豪,RoseC">
  <meta name="baidu-site-verification" content="code-2LJIrA8S4z" />
  <title>Express+Multer图片上传 - RoseC的博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.5.3/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.1.2/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"rose-ccc.gitee.io","root":"/","version":"1.8.5","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"copy_btn":true,"image_zoom":{"enable":true},"lazyload":{"enable":true,"onlypost":false},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>RoseC</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/indexImg/index.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Express+Multer图片上传">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-02-06 23:49" pubdate>
        2021年2月6日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      754 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      11
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Express+Multer图片上传</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2021年2月7日 凌晨
                
              </p>
            
            <div class="markdown-body">
              <p>项目中总会需要文件上传的功能，实现这个功能的时候，我有下面两个思路:  </p>
<ol>
<li>将图片转为base64，再将base64码存入数据库，调用的时候直接渲染即可</li>
<li>将图片上传到服务器作为静态资源暴露出来，再将图片的访问链接存入数据库，调用的时候使用该链接去访问  </li>
</ol>
<p>我们来分析一下上面两种方法:</p>
<ol>
<li>使用base64，可以减少http请求，获取请求结果后直接编码渲染，但是也有弊端，base64一般会比原图要大一些，且浏览器需要解码才能显示图片</li>
<li>第二张方法获取请求结果后，需要将请求结果中的图片链接拿来，再发送请求，之后渲染图片  </li>
</ol>
<p>权衡利弊下，我选择了第二种方法进行图片上传</p>
<h3 id="运行环境"><a href="#运行环境" class="headerlink" title="运行环境"></a>运行环境</h3><p>node + express</p>
<h3 id="依赖插件：Multer"><a href="#依赖插件：Multer" class="headerlink" title="依赖插件：Multer"></a>依赖插件：Multer</h3><p>Multer 是一个 node.js 中间件，用于处理 multipart/form-data 类型的表单数据（请求头”Content-Type”: “multipart/form-data;”），它主要用于上传文件。<br>Multer 会添加一个 body 对象 以及 file 或 files 对象 到 express 的 request 对象中。 body 对象包含表单的文本域信息，file 或 files 对象包含对象表单上传的文件信息。</p>
<h3 id="废话不多说，直接贴代码"><a href="#废话不多说，直接贴代码" class="headerlink" title="废话不多说，直接贴代码"></a>废话不多说，直接贴代码</h3><h4 id="前端"><a href="#前端" class="headerlink" title="前端"></a>前端</h4><pre><code class="hljs bash">&lt;script src=<span class="hljs-string">&quot;https://unpkg.com/axios/dist/axios.min.js&quot;</span>&gt;&lt;/script&gt;
&lt;input <span class="hljs-built_in">type</span>=<span class="hljs-string">&quot;file&quot;</span> id=<span class="hljs-string">&quot;up&quot;</span> multiple /&gt;
&lt;script&gt;
	var up = document.getElementById(<span class="hljs-string">&quot;up&quot;</span>)
	up.onchange = <span class="hljs-keyword">function</span>(res) &#123;
		<span class="hljs-built_in">let</span> fs = up.files;
		var forms = new FormData()
		forms.append(<span class="hljs-string">&#x27;file&#x27;</span>, fs[0])
		console.log(fs[0])
		axios(&#123;
			url: <span class="hljs-string">&#x27;http://服务器地址:3000/upload&#x27;</span>,
			method: <span class="hljs-string">&#x27;post&#x27;</span>,
			headers: &#123;
				<span class="hljs-string">&quot;Content-Type&quot;</span>: <span class="hljs-string">&quot;multipart/form-data;&quot;</span>
			&#125;,
			data: forms,
			success: (res) =&gt; &#123;
				console.log(res)
			&#125;
		&#125;).<span class="hljs-keyword">then</span>(res =&gt; &#123;
			console.log(res)
		&#125;)
	&#125;		
&lt;/script&gt;</code></pre>
<h4 id="后台"><a href="#后台" class="headerlink" title="后台"></a>后台</h4><pre><code class="hljs bash">const express = require(<span class="hljs-string">&#x27;express&#x27;</span>)
const app = express()
const multer = require(<span class="hljs-string">&#x27;multer&#x27;</span>)
const port = 3000 // 端口号

// 文件操作
const fs = require(<span class="hljs-string">&#x27;fs&#x27;</span>)
const path = require(<span class="hljs-string">&#x27;path&#x27;</span>)

// 使用multer插件，设置文件上传的路径
const upload = multer(&#123;
	dest: <span class="hljs-string">&#x27;data/&#x27;</span>
&#125;);

// 配置静态资源路径
app.use(express.static(path.join(__dirname, <span class="hljs-string">&#x27;data&#x27;</span>)));

// 解决跨域
app.all(<span class="hljs-string">&#x27;*&#x27;</span>, <span class="hljs-keyword">function</span>(req, res, next) &#123;
	res.header(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);
	res.header(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;Content-Type&#x27;</span>);
	res.header(<span class="hljs-string">&#x27;Access-Control-Allow-Methods&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);
	res.header(<span class="hljs-string">&#x27;Content-Type&#x27;</span>, <span class="hljs-string">&#x27;application/json;charset=utf-8&#x27;</span>);
	next();
&#125;);

// 处理post图片上传上来的数据
app.post(<span class="hljs-string">&#x27;/upload&#x27;</span>, upload.any(), <span class="hljs-keyword">function</span>(req, res, next) &#123;
	console.log(req.files[0]); // 上传的文件信息

	var des_file = <span class="hljs-string">&quot;./data/&quot;</span> + req.files[0].originalname;
	// req.files[0].path即 multer设置的文件上传的路径
	fs.readFile(req.files[0].path, <span class="hljs-keyword">function</span>(err, data) &#123;
		fs.writeFile(des_file, data, <span class="hljs-keyword">function</span>(err) &#123;
			<span class="hljs-keyword">if</span> (err) &#123;
				console.log(err);
			&#125; <span class="hljs-keyword">else</span> &#123;
				response = &#123;
					message: <span class="hljs-string">&#x27;File uploaded successfully&#x27;</span>,
					filename: req.files[0].originalname
				&#125;;
				console.log(response);
				res.send(&#123;
					data: JSON.stringify(response),
					info: <span class="hljs-string">&quot;aaaa&quot;</span>
				&#125;);
				// 删除原来multer存的文件
				fs.unlinkSync(req.files[0].path)
			&#125;
		&#125;);
	&#125;);
&#125;);

app.listen(port, () =&gt; console.log(`服务器启动成功，端口号为： <span class="hljs-variable">$&#123;port&#125;</span>!`))</code></pre>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%90%8E%E5%8F%B0/">后台</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Node/">Node</a>
                    
                      <a class="hover-with-bg" href="/tags/Express/">Express</a>
                    
                      <a class="hover-with-bg" href="/tags/multer/">multer</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/02/24/vue%E5%A4%9A%E9%A1%B5%E9%9D%A2%E7%A8%8B%E5%BA%8F%E9%85%8D%E7%BD%AE/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">vue多页面程序配置</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/01/07/Javascript%E6%B7%B1%E6%B5%85%E6%8B%B7%E8%B4%9D%E9%97%AE%E9%A2%98/">
                        <span class="hidden-mobile">Javascript深浅拷贝问题</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":200})
    NProgress.start()
    document.addEventListener('DOMContentLoaded', function() {
      window.NProgress && window.NProgress.inc();
    })
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.5.3/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script  src="https://cdn.staticfile.org/tocbot/4.12.0/tocbot.min.js" ></script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "/local-search.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
